package javapop.framework.parser;

import javapop.framework.ParseContext;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class Maybe<T> extends Parser<MaybeParse<T>> {
	protected Parser<T> child;
	
	public Maybe(Parser<T> child) {
		this.child = child;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<MaybeParse<T>> eval(ParseContext<?> ctx, ParseInput input) {		
		ParseResult<T> result = child.parse(ctx,input);
		if(result.isError()) {
			if(result.asError().isFatal()) {
				return (ParseResult<MaybeParse<T>>) result;
			}
			return buildResult(new MaybeParse<T>());
		} else {	
			return buildResult(new MaybeParse<T>(result));
		}
	}
			
	@Override
	public String getDescription() {
		StringBuffer buf = new StringBuffer();
		buf.append("(");
		buf.append(child.getDescription());
		buf.append(")?");
		return buf.toString();
	}
	
	@Override
	public boolean isMemoized() {
		return false;
	}
}
